{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "baedb638",
   "metadata": {},
   "source": [
    "# 优化百度ASR接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "105079bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e7d50eba",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.c1b41e93b86fe95b98b460768e0491ff.2592000.1659084984.282335-26290537'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取token\n",
    "API_KEY = '37gIu5l6VVdtGkVLrCYi7hfu'\n",
    "SECRET_KEY = 'dE0Bd5QKvxssZ8VzYMRhL19IcH5T71bU'\n",
    "\n",
    "token = fetch_token(API_KEY,SECRET_KEY)\n",
    "token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e28eeb9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96256c96",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = eval(asr(token = token, AUDIO_FILE = '1.wav'))['result'][0]\n",
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f84fe55e",
   "metadata": {},
   "source": [
    "# 图灵机器人API测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "1d82b519",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests,json\n",
    "\n",
    "TL_key = \"d5d5bb66f66d4da8bedb378df7adfa70\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "164cc10a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def TL_API(TL_key,text):\n",
    "    TL_url = 'http://openapi.turingapi.com/openapi/api/v2'\n",
    "    payload={\n",
    "        \"reqType\":0,\n",
    "        \"perception\": {\n",
    "            \"inputText\": {\n",
    "                \"text\": text\n",
    "            },\n",
    "        },\n",
    "        \"userInfo\": {\n",
    "            \"apiKey\": TL_key,\n",
    "            \"userId\": \"0000001\"\n",
    "        }\n",
    "    }\n",
    "    payload_json = json.dumps(payload)\n",
    "    res = requests.post(TL_url,data=json.dumps(payload))\n",
    "    return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cba30044",
   "metadata": {},
   "source": [
    "# 用图灵接口的语音识别对话机器人\n",
    "1. 准备音频文件\n",
    "2. 调用百度语音识别-返回文本信息\n",
    "3. 调用图灵机器人-返回文本信息\n",
    "4. 调用百度语音合成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "55446c82",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pydub\n",
      "  Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n",
      "Installing collected packages: pydub\n",
      "Successfully installed pydub-0.25.1\n"
     ]
    }
   ],
   "source": [
    "!pip install pydub"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "e0a65cd3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tts api  error:{\"err_detail\":\"16: Open api characters limit reached\",\"err_msg\":\"16: Open api characters limit reached\",\"err_no\":502,\"err_subcode\":16,\"tts_logid\":1114310838}\n",
      "\n",
      "result saved as :error.txt\n"
     ]
    }
   ],
   "source": [
    "import TTS\n",
    "TTS.tts(token,\"好困啊\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "e925377f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "TEXT = \"欢迎使用百度语音合成。\"\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 1\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 7\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 8\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 6\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "def tts(token,text):\n",
    "    tex = quote_plus(text)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)\n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "750472b2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "529a54ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "import TTS\n",
    "import speech_recognition\n",
    "from pydub import AudioSegment\n",
    "from pydub.playback import play\n",
    "\n",
    "# 准备音频文件\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "\n",
    "# 调用百度语音识别\n",
    "token = ASR.fetch_token(API_KEY,SECRET_KEY)\n",
    "result = eval(ASR.asr(token))['result'][0]\n",
    "\n",
    "# 调用图灵机器人\n",
    "# robot(robot_key, result)\n",
    "\n",
    "# 调用青云客机器人\n",
    "robot2(result)\n",
    "\n",
    "# 语音合成\n",
    "# TTS.tts(token,robot(robot_key, result))\n",
    "TTS.tts(token, robot2(result))\n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f07b3548",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
